//
//  CategoryViewController.m
//  AmazingShopping
//
//  Created by Tan on 4/18/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "CategoryViewController.h"
#import "ProductListViewController.h"

@interface CategoryViewController ()

@end

@implementation CategoryViewController

@synthesize tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
    [self getCategoryArray];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTableView:nil];
    [super viewDidUnload];
}

- (void)getCategoryArray{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/get_category_list", serverPath]];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
}

#pragma mark ASIHTTPRequest Delegates
- (void)requestFailed:(ASIHTTPRequest *)request{
    
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    NSData *data = [request responseData];
    JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
    categoryArray = [jsonDecoder objectWithData:data];
    [self.tableView reloadData];
}

#pragma mark Table View Data Source

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [categoryArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Category"];
    int row = [indexPath row];
    cell.textLabel.text = [[categoryArray objectAtIndex:row] valueForKey:@"category_name"];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

#pragma mark Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = [indexPath row];
    ProductListViewController *nextController = [[ProductListViewController alloc]init];;
    [nextController setCategoryID: [[categoryArray objectAtIndex:row] valueForKey:@"category_id"]];
    nextController.navigationItem.title = [[categoryArray objectAtIndex:row] valueForKey:@"category_name"];
    [self.navigationController pushViewController:nextController animated:YES];
}

@end
